﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace Tsanie.OsuDevice.Components {
    class SubItemSorter : IComparer {
        public int ColumnIndex { get; private set; }
        public int SortType { get; private set; }
        public bool Asc { get; private set; }

        public SubItemSorter(int ColumnIndex, bool Asc, int SortType) {
            this.ColumnIndex = ColumnIndex;
            this.Asc = Asc;
            this.SortType = SortType;
        }

        int IComparer.Compare(object x, object y) {
            ListViewItem lv_x = x as ListViewItem;
            ListViewItem lv_y = y as ListViewItem;
            if (lv_x == null || lv_y == null)
                return 0;
            string s1 = lv_x.SubItems[ColumnIndex].Text.Trim();
            string s2 = lv_y.SubItems[ColumnIndex].Text.Trim();
            int rtn = 0;
            if (!Asc) {
                // 逆序
                string tmp = s1;
                s1 = s2;
                s2 = tmp;
            }

            if (SortType == 0) {
                // 字符排序
                rtn = string.Compare(s1, s2);
            } else if (SortType == 1) {
                // 数值排序
                double d1 = 0, d2 = 0;
                if (s1 == "")
                    return 0;
                else if (s2 == "")
                    return 1;
                try {
                    d1 = double.Parse(s1);
                    d2 = double.Parse(s2);
                } catch { return 0; }
                if (d1 < d2)
                    return 0;
                else
                    return 1;
            } else if (SortType == 2) {
                // 日期排序
                DateTime t1, t2;
                try {
                    t1 = DateTime.Parse(s1);
                    t2 = DateTime.Parse(s2);
                } catch { return 0; }
                if (t1 < t2)
                    return 0;
                else
                    return 1;
            }
            return rtn;
        }
    }
}
